$(function(){
	var grid;
	var states = {NORMAL:"正常",LACK:"缺货",HALT:"停售"};
	grid = $("#productGird").datagrid({
		fit:true,
		border:false,
		singleSelect:true,
		fitColumns:true,
		/* 显示分页工具栏 */
		pagination:true,
		/* 奇偶行使用不同背景色 */
		/* striped:true, */
	    url:'product/list',
	    idField:'id',
	    toolbar:"#proToolbar",
	    columns:[[
	        {title:'编号',field:'id',width:100},
	        {title:'产品名',field:'name',width:180},
	        {title:'产品图片',field:'image',width:50,
	        	formatter:function(value,row,index){
	        		return '<a id="pimg" href="javascript:void(0);" onclick="bigImg('+"'"+ value +"'"+ ');"><img src="' + value + '" alt="无图片" title="点击查看大图" style="height:38px;width:50px;"></a>';
	        }},
	        {title:'状态',field:'state',width:100,formatter:function(value,row,index){
	        		return states[value];
	        }},
	        {title:'供应商',field:'supplier',width:180,
	        	formatter:function(value,row,index){
	        		return value.name;
	        }},
	        {title:'库存',field:'stock',width:100},
	        {title:'销售价',field:'sellPrice',width:100,formatter:function(value,row,index){
        		return "￥"+value;
       		}},
	        {title:'成本价',field:'costPrice',width:100,formatter:function(value,row,index){
        		return "￥"+value;
       		}}
	    ]]
	    
	});
	
	$("#proToolbar a.all").click(function() {
		$("#proToolbar #productState").combobox("setValue","");
		$("#productSear").searchbox("setValue","");
		$('#productGird').datagrid("load",{});
	})
	
	$("#proToolbar #productState").combobox({
		valueField: 'id',
		textField: 'text',
		data:[{
		    "id":"",
		    "text":"请选择状态"
		},{
		    "id":"NORMAL",
		    "text":"正常"
		},{
		    "id":"LACK",
		    "text":"缺货"
		},{
		    "id":"HALT",
		    "text":"停售",
		}],
		onChange: function(before,after){
			var value = $("#proToolbar #productSear").searchbox('getValue');
			var name = $("#proToolbar #productSear").searchbox('getName');
			doSearch(value,name);
	    }
	});

	// 为工具栏的按钮绑定事件
	$("#proToolbar").on("click","a.add",function(){
		var dialog = $("<div/>").dialog({
			title: "新增产品",
			width: 450,
			height: 500,
			modal:true,
			href:'product/form',
			onClose: function(){
				//关闭窗户后，立即销毁窗口
				$(this).dialog("destroy");
			},
			buttons:[
				{
					iconCls:"icon-ok",
					text:"保存",
					handler:function(){

						var uploader = $("#uploader");
						var form = $("#productForm");
						var file = $("#upimg").get(0).files[0];
						console.log(file);
						
						if(file){
							var formData = new FormData();
							formData.append("upload_file",file);
							$.ajax({
								url:"product/upload",
								type:"POST",
								data:formData,
								contentType:false,
								processData:false,
								success:function(data){
									if(data.success){
										form.append('<input type="hidden" name="image" value="'+data.file_path+'">');
										//校验表单数据
										if(form.form("validate")){
											$.post("product/save",form.serialize(),function(rs){
												if(rs.err){
													alert(rs.err);
												}else{
													alert("保存成功！");
													//关闭当前窗口
													dialog.dialog("close");
													grid.datagrid("reload");
												}
											});
										}
									}else{
										alert(data.msg);
									}
								}
							});
						}else{
							form.append('<input type="hidden" name="image" value="static/image/product/null.png">');
							//校验表单数据
							if(form.form("validate")){
								$.post("product/save",form.serialize(),function(rs){
									if(rs.err){
										alert(rs.err);
									}else{
										alert("保存成功！");
										//关闭当前窗口
										dialog.dialog("close");
										grid.datagrid("reload");
									}
								});
							}
						}
					}
				},
				{
					iconCls:"icon-cancel",
					text:"取消",
					handler:function(){
						dialog.dialog("close");
					}
				}
			]
		});
	}).on("click","a.edit",function(){
		var row = grid.datagrid("getSelected");
		if(row){
			var dialog = $("<div/>").dialog({
				title: "编辑用户",
				width: 450,
				height: 400,
				modal:true,
				href:'product/form/'+row.id,
				onClose: function(){
					//关闭窗户后，立即销毁窗口
					$(this).dialog("destroy");
				},
				buttons:[
					{
						iconCls:"icon-ok",
						text:"保存",
						handler:function(){

							var uploader = $("#uploader");
							var form = $("#productForm");
							var file = $("#upimg").get(0).files[0];
							console.log(file);
							
							if(file){
								var formData = new FormData();
								formData.append("upload_file",file);
								$.ajax({
									url:"product/upload",
									type:"POST",
									data:formData,
									contentType:false,
									processData:false,
									success:function(data){
										if(data.success){
											form.append('<input type="hidden" name="image" value="'+data.file_path+'">');
											//校验表单数据
											if(form.form("validate")){
												$.post("product/save",form.serialize(),function(rs){
													if(rs.err){
														alert(rs.err);
													}else{
														alert("保存成功！");
														//关闭当前窗口
														dialog.dialog("close");
														grid.datagrid("reload");
													}
												});
											}
										}else{
											alert(data.msg);
										}
									}
								});
							}else{
								form.append('<input type="hidden" name="image" value="static/image/product/null.png">');
								//校验表单数据
								if(form.form("validate")){
									$.post("product/save",form.serialize(),function(rs){
										if(rs.err){
											alert(rs.err);
										}else{
											alert("保存成功！");
											//关闭当前窗口
											dialog.dialog("close");
											grid.datagrid("reload");
										}
									});
								}
							}
						}
					},
					{
						iconCls:"icon-cancel",
						text:"取消",
						handler:function(){
							dialog.dialog("close");
						}
					}
				]
			});
		}else{
			alert("请选择要操作的行");
		}
	}).on("click","a.delete",function(){
		var row = grid.datagrid("getSelected");
		if(row){
			$.messager.confirm('删除提示', '确认删除此记录?', function(r){
                if (r){
                    $.get("product/delete/"+row.id,function(){
                    		grid.datagrid("reload");
                    }).error(function(){
                    		$.messager.alert("提示","系统错误,删除失败!");
                    });
                }
            });
		}else{
			alert("请选择要操作的行");
		}
	});
	
	$('#productSear').searchbox({
	    searcher:doSearch,
	    width:300,
	    menu:'#pp',
	    prompt:'请输入查询内容'
	});
	
});
function bigImg(value){
	var dialog = $("<div/>").dialog({
		width:400,
		height:441,
		border:false,
		modal:true,
		noheader:true,
		maximizable:true,
		revert:true,
		onClick:function(){
			dialog.dialog("close");
		},
		onClose: function(){
			//关闭窗户后，立即销毁窗口
			$(this).dialog("destroy");
		},

		content:'<img alt="加载失败" title="点击图片关闭大图" style="text-align: center;width:400px;height:400px" src="' + value + '" >'
	});
	dialog.click(function(){
		dialog.dialog("close");
	});
}

function doSearch(value,name){
	var param = {};
	param[name] = value;
	param["state"] = $("#proToolbar #productState").combobox("getValue");
	$('#productGird').datagrid('load', param);
}
